<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
</head>
<body>
<button onclick="testGet()">GET请求</button>
<button onclick="testPost()">POST请求</button>
<button onclick="testPut()">PUT请求</button>
<button onclick="testDelete()">DELETE请求</button>
<script>
    function testGet() {
        axios({
            url:'http://localhost:3000/posts',
            methods:'GET',
            params:{
                id:1,
                xxx:'abc'
            }
        }).then(
            response=>{
                console.log(response)
            },
            error=>{
                console.log(error)
                console.log(error.message)
            }
        )
    }

    // post请求 服务器端保存数据
    function testPost() {
        axios({
            url:'http://localhost:3000/posts',
            methods:'POST',
            data:{
                "title": "json-server----",
                "author": "typicode----"
            }
        }).then(
            response=>{
                console.log(response)
            },
            error=>{
                console.log(error.message)
            }
        )
    }

    // PUT请求 服务器端更新数据
    function testPut() {
        axios({
            url:'http://localhost:3000/posts/1',
            methods:'PUT',
            data:{
                "title": "json-server----PUT",
                "author": "typicode----PUT"
            }
        }).then(
            response=>{
                console.log(response)
            },
            error=>{
                console.log(error.message)
            }
        )
    }
    // DELETE请求 服务器端更新数据
    function testDelete() {
        axios({
            url:'http://localhost:3000/posts/2',
            methods:'delete'
        }).then(
            response=>{
                console.log(response)
            },
            error=>{
                console.log(error.message)
            }
        )
    }

    function axios({
        url,
        methods='GET',
        params={},
        data={}
    }) {
        // 返回一个promise对象
        return new Promise((resolve,reject)=>{
            // 处理methods 转大写
            methods=methods.toUpperCase()

            // 处理query参数 拼接到url上 id=1&xxx=abc
            let queryString=''
            Object.keys(params).forEach(key=>{
                queryString+=`${key}=${params[key]}&`
            })
            if (queryString){
                // 去除最后的&
                queryString=queryString.substring(0,queryString.length-1)
                // 接到URl
                url+='?'+queryString
            }

            // 1.执行异步ajax请求
            // 创建xhr对象
            const request = new XMLHttpRequest()
            // 打开连接 初始化请求
            request.open(methods,url,true)
            // 发送请求
            if (methods==='GET' || methods==='DELETE'){
                request.send()
            } else if (methods==='POST' || methods==='PUT'){
                // 告诉服务器请求体格式
                request.setRequestHeader('Content-Type','application/json;charset=utf-8')
                // 发送json格式请求体参数
                request.send(JSON.stringify(data))
            }

            // 绑定状态改变的监听
            request.onreadystatechange=function () {
                // 如果请求没有完成 直接结束
                if (request.readyState!==4){
                    return false
                }
                // console.log(request)
                // 如果响应状态码在[200,299]之间代表成功 否则失败
                const {status,statusText} = request
                // 2.1如果请求成功了，调用resolve
                // console.log(status)
                if (status>=200 && status <=299 ){
                    // 准备结果数据对象response
                    const response={
                        data:JSON.parse(request.response),
                        status,
                        statusText
                    }
                    resolve(response)
                }else {// 2.2如果失败了，调用reject
                    reject(new Error('request error status is '+status))
                }
            }

        })
    }

    axios({
        url:'/xxx'
    })
</script>
</body>
</html>
